import BaseServer from "../../engine/server";
import { nilV, Useful, errorHandle, BaseErr } from "utils";

import type {
    ResponseInterceptorItem,
    InnerRequestConfig,
    ResponsePass,
} from "../../engine/types/engine.type";

let InstanceAppServer: AppServer | null = null;

// 检查状态码
function checkStatusCode(res: any): BaseErr | undefined {
    let { statusCode } = res || {};
    if (Useful.number(statusCode)) {
        // 有 code
        // 判断 状态码是否正确
        if (statusCode >= 200 && statusCode <= 300) {
            return;
        }
        // 错误码 有问题
        return errorHandle.insideErr(res);
    }
    // 没有状态码 不管
    return;
}

class AppServer extends BaseServer {
    constructor(arg?: InnerRequestConfig) {
        super(arg);
        // TODO  请求拦截器 添加签名

        // TODO 要添加401 拦截器
        // 添加响应拦截器
        this.addResponseCheck();
    }

    // 这里要 拦截 401 请求
    request(configuration: InnerRequestConfig): void {
        // TODO 这里 要 想 , 如何 成功了 在 success
        // 如果 401 fail  , 就重试
        super.request(configuration);
    }

    // 添加响应拦截器
    addResponseCheck() {
        let checker: ResponseInterceptorItem = {
            name: "data-check",
            handler(dataPass: ResponsePass) {
                let { config, res } = dataPass;
                // 检查状态码
                let statusCodeErr = checkStatusCode(res);
                if (statusCodeErr) {
                    throw statusCodeErr;
                }
                // 检查 返回的 errorCode
                let { data: resData } = res || {};
                let { errCode, data } = resData || {};
                if (errCode !== 0) {
                    throw errorHandle.insideErr(resData);
                }
                let returnRes: ResponsePass = {
                    config: config,
                    res: data,
                };
                return returnRes;
            },
        };
        this.responseInterceptor.use(checker);
    }

    // customRequestHeader(): Record<string, string> {
    //     // TODO 添加签名
    //     let timeStamp = Date.now();

    //     return { timeStamp: `${timeStamp}` };
    // }

    // 用单例吧
    static get appServer(): AppServer {
        if (nilV(InstanceAppServer)) {
            InstanceAppServer = new AppServer();
            return InstanceAppServer;
        }
        return InstanceAppServer!;
    }
}

export default AppServer;
